<?php
class episode extends Model{
	public static function getTableName(){
		return 'episode';
	}

	public function set($object){
		$this->programme_id = !isset($object->programme_id) ? '0' : $object->programme_id;
		$this->onair_episode_no = !isset($object->onair_episode_no) ? '0' : trim($object->onair_episode_no);
		$this->original_episode_no = !isset($object->original_episode_no) ? '0' : trim($object->original_episode_no);
		$this->average_rating = !isset($object->average_rating) ? '0' : trim($object->average_rating);
		$this->first_time_onair = !isset($object->first_time_onair) ? '' : $object->first_time_onair;
		$this->publish_datetime = !isset($object->publish_datetime) ? '' : $object->publish_datetime;
		$this->expire_datetime = !isset($object->expire_datetime) ? '' : $object->expire_datetime;
		$this->other_language_episodes = !isset($object->other_language_episodes) ? '' : trim($object->other_language_episodes);
		$this->highlighted_cast_roles = !isset($object->highlighted_cast_roles) ? '' : $object->highlighted_cast_roles;
		$this->casts = !isset($object->casts) ? '' : $object->casts;
		$this->available_tag_types = !isset($object->available_tag_types) ? '' : $object->available_tag_types;
		$this->tags = !isset($object->tags) ? '' : $object->tags;
		$this->folders = !isset($object->folders) ? '' : $object->folders;
		$this->status = !isset($object->status) ? '0' : $object->status;
		$this->created_at = !isset($object->created_at) ? '' : $object->created_at;
		$this->created_by = !isset($object->created_by) ? '' : $object->created_by;
		$this->modified_at = !isset($object->modified_at) ? '' : $object->modified_at;
		$this->modified_by = !isset($object->modified_by) ? '' : $object->modified_by;
	}

	public function getDetails($episode_id)
	{
        $sql = "
            select 
                a.* , 
                b.* 
            from
                ".self::getTableName()." a 
            left join 
                `episode-language` b on a.id=b.episode_id 
            where 
                episode_id='{$episode_id}' group by episode_id";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);

        $sql = "SELECT * FROM `episode-language` WHERE `episode_id` = " . $episode_id;
        $ro = Model::$dbo['r']->findBySql(__class__, $sql);
        foreach ($ro as $obj) {
            $episode_language[$obj->language_id] = $obj;
        }
		
        $num_language_en = language::getLanguageId(AC::LANGUAGE_EN);
        if (!isset($episode_language[$num_language_en])) {
            $episode_language[$num_language_en]->title = '';
            $episode_language[$num_language_en]->description = ''; 
            $episode_language[$num_language_en]->description_short = '';
        }
        $ret[0]->episode_language = $episode_language;
		return $ret[0];
	}

	public function getEpisode($episode_id)
	{
        $sql = "
            select 
                a.* 
            from
                ".self::getTableName()." a 
            where 
                id='{$episode_id}' group by id";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
       	return $ret[0];
	}

	public static function getEpisodeID($programme_id, $onair_episode_no)
	{
	    $sql = "select id from ".self::getTableName()." where onair_episode_no='{$onair_episode_no}' and programme_id='{$programme_id}'";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		return isset($ret[0]) ? $ret[0]->id : '';
    }

    public static  function getEpisodeNumByProgrammeId($pid)
    {
        $sql = 'select onair_episode_no from episode where `status`!='. AC::STATUS_DELETED .' AND programme_id = :pid';
        $params = array(':pid'=>$pid);
        $result = Model::selectBySql($sql,$params);
        $epis  = array();
        if(!empty($result))
        {
            foreach($result as $epi)
            {
                $epis[] = $epi['onair_episode_no'];
            }
        }
        $ret  = implode(',',$epis);
        return $ret;
    }


	public function getList()
	{
		$sql = "select * from ".self::getTableName()." a left join `episode-language` b on a.id=b.episode_id";
		return Model::$dbo['r']->findBySql(__class__, $sql);
	}

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx	= NULL, $sord = NULL, $unpublish = 0)
	{
		$find	=	$findRelation['mapField'];
		$db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $titleWhere =   $programmeTitleIds  =   NULL;
        $pathWhere  =   NULL;
        $searchSing =   FALSE;
        $programmes =   array();
        $resField   =   $resOperation   =   $resValue   =   array();

        foreach ($field as  $fieldKey   =>  $fieldValue) {
            switch ($fieldValue) {
            case 'title':
                $titleWhere[]   =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                break;
            case 'path':
                $pathWhere[]    =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                break;
            case 'premium':
                if ($value[$fieldKey] != '2') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            case 'premium_items':
                if (isset($value[$fieldKey]) && is_array($value[$fieldKey])) {
                    foreach ($value[$fieldKey] as $_value) {
                        if ($_value == 'subscription_flag') {
                            $where_extra[] = '`subscription_flag`=1';
                        } else if ($_value == 'ppv_flag') {
                            $where_extra[] = '`ppv_flag`=1';
                        }
                    }
                }
                break;
            case 'video_type':
                if ($value[$fieldKey] != 'all') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            default:
                $resField[$fieldKey]    =   $fieldValue;
                $resOperation[$fieldKey]=   $operation[$fieldKey];
                $resValue[$fieldKey]    =   $value[$fieldKey];
                break;
            }
        }

        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation);
        }
        if (!empty($pathWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByPath($pathWhere);
        }

        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   

            if (empty($programmeTitleIds))  $programmeTitleIds  =   '""';
            $programmeTitleIds  =   ' WHERE `programme-language`.programme_id IN ('. $programmeTitleIds. ')';
        }
		$where	=	Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		if (!empty($where))
		{
			$where	=	' WHERE '. $where;
        } else {
            $where = ' WHERE 1';
        } 

        if (!empty($where_extra)) {
            $where .= ' AND ' . implode(' AND ', $where_extra);
        }

        $subSql	=	'
            SELECT DISTINCT
                `episode`.id					AS	id,
                `episode`.programme_id          AS  programme_id,
                GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")	AS	title,
                `episode`.onair_episode_no		AS	onair_episode_no,
                `episode`.first_time_onair	    AS	premier_time_onair,
                `episode`.status                AS  record_status,
                `episode`.modified_at			AS	modified_at,
                `episode`.modified_by			AS	modified_by,
                `programme`.premium_flag AS premium,
                `programme`.video_type AS video_type,
                `programme_premium`.ppv_flag,
                `programme_premium`.subscription_flag
            FROM episode 
            LEFT JOIN `programme` ON (`episode`.programme_id = `programme`.id)
            LEFT JOIN `programme_premium` ON (`episode`.programme_id = `programme_premium`.programme_id)
            INNER JOIN `programme-language`	ON (`episode`.programme_id = `programme-language`.programme_id)
            '. $programmeTitleIds. '
            GROUP BY id
            ';

		$sql=	'
			SELECT
				id,
                programme_id,
				title,
				onair_episode_no,
                record_status,
				premier_time_onair,
				modified_at,
				modified_by
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                if ('path'  ==  $value)     continue;
                $orderBy[]  =   $find[$value];
            }
        }

        if (empty($orderBy))    $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)
		{
			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();

			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);
			$gridData->premier_time_onair = str_replace(' ','<br />',$gridData->premier_time_onair);

            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                $publish_log = publish_log::getPublishLog(__class__, $gridData->id);
                if (property_exists($publish_log, 'non_premium')) {
                    $publish = Model::object2array($publish_log->non_premium); 
                } else {
                    $publish = array();
                }

                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }

			foreach ($find	as	$name	=>	$column) {
                switch ($name) {
                case 'programme_id':
                case 'path':
                case 'premium':
                case 'premium_items':
                case 'video_type':
                    break;
                default:
                    $tmp['cell'][] = $gridData->$name;
                    break;
                }
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED !=   $originalStatus &&  empty($unpublish))
            {
                $delEdit    =	'<a title="Edit" href="get_episode.html?act=edit&step=2&id='. $gridData->id. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_episode.html?act=view&step=2&id='. $gridData->id. '&unpublish='. $unpublish. '" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $tmp['cell'][]  =   $delEdit. $delView;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}
		return	$list;
	}

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id)
    {
        if (empty($id)) return  array();
        $sqlArr =   array(
                    'episode'           =>  array('id = "'. $id. '"'),
                    'episode-language'  =>  array('episode_id = "'. $id. '"'),
                    'episode-video'     =>  array('episode_id = "'. $id. '"'),
                );

        $sqlArray   =   array();
        foreach ($sqlArr    as  $tableName  =>  $whereArray)
        {
            $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }

	/*
	 * by donald 
	 * modified at 2011-09-23
	 * bug 6636
	 */
	public static function publish($episode_id)
	{
		$episode = new episode();
		$episode = $episode->get($episode_id);

		$programme = new programme();
		$programme = $programme->get($episode->programme_id);
		$nunPremium = publish_log::getNonPremiumPublishLog('programme',$programme->id);
		$log_id = CommonUtils::save_log('episode', $episode_id, AC::LOG_OP_PUBLISHING, json_encode($episode));

		if (!empty($nunPremium) && $nunPremium->status == AC::STATUS_PUBLISH) {
			$publish_log_detail = publish_log::getNonPremiumPublishLog('episode', $episode_id);
			if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH) {
				$proof = new ProofreadSend();
				$proof_flag = $proof->getProofread(Model::$dbo['r']->getDbHandle(), 'episode', $episode_id, $log_id);
				if ($proof_flag !== TRUE) {
					return $proof_flag;
				}
				$publish_type = 'old';
			} else {
				$publish_type = 'new';
			}
		} else {
			return '0201';
		}

		if ($programme->premium_flag) {
			$Premium = publish_log::getPremiumPublishLog('programme',$programme->id);
			if (!empty($Premium) && $Premium->status == AC::STATUS_PUBLISH_PREMIUM) {
				$publish_log_detail = publish_log::getPremiumPublishLog('episode', $episode_id);
				if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH_PREMIUM) {
					$proof = new P_ProofreadSend();
					$proof_flag = $proof->getProofread(Model::$dbo['r']->getDbHandle(), 'episode', $episode_id, $log_id);
					if ($proof_flag !== TRUE) {
						return $proof_flag;
					}
					$publish_type .= 'old';
				} else {
					$publish_type .= 'new';
				}
			} else {
				return '0201';
			}
		}

		//new flow
		if ($publish_type != 'old' && $publish_type != 'oldold') {
			$proof = new NewProofreadSend;
			$proof_flag = $proof->getProofread(
				Model::$dbo['r']->getDbHandle(), 
				'episode', 
				$episode_id, 
				$log_id,
				TRUE,
				$publish_type
			);
		}

		//remove change_log if go old flow
		switch ($publish_type) {
			case 'old':
			case 'oldold':
			case 'oldnew':
			case 'newold':
				change_log::remove(array('episode_id' => intval($episode_id)));
				break;
			default:
				break;
		}

		return $proof_flag;
	}

	/*
	 * by donald
	 * at 2011-09-23
	 */
	public static function getEpisodeIdForChangeLog($folder_id, $episode_ids)
	{
		if (empty($episode_ids)) {
			return array();
		}

		foreach ($episode_ids as $episode_id) {
			$episode = new episode;
			$episode_detail = $episode->get($episode_id);

			$folders = array();
			$folders[] = $episode_detail->folders;

			$casts = json_decode($episode_detail->casts, TRUE);
			foreach ($casts as $cast_list) {
				foreach ($cast_list as $cast) {
					$cast_id = $cast['cast_id'];
					if (!empty($cast_id)) {
						$cast = new cast;
						$cast_detail = $cast->get($cast_id);
						if (!empty($cast_detail->folders)) {
							$folders[] = $cast_detail->folders;
						}
					}
				}
			}

			$folders = explode(',', implode(',', $folders));

			if (in_array($folder_id, $folders)) {
				return array($episode_id);
			}
		}

		return array();
	}

	/*
	 * by donald
	 * at 2011-10-25
	 */
	public static function getAll(array $params)
	{
		foreach ($params as $field => $value) {
			switch ($field) {
				case 'programme_id':
					$where[] = 'programme_id = ?';
					$where_array[] = $value;
					break;
				case 'status':
					$where[] = 'status = ?';
					$where_array[] = $value;
					break;
			}
		}

		return self::$dbo['w']->find(__CLASS__, implode(' AND ', $where), $where_array);
	}
}
?>
